﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rated.DAL.Db;
using System.Collections.Specialized;

namespace Rated.DAL.Repository
{
    public static class ReviewRepository
    {
        public static Review Add(NameValueCollection itemValues)
        {
            return StoreValues(itemValues);
        }

        public static Review StoreValues(NameValueCollection itemValues)
        {
            var db = new RatedEntities();
            var reviewId = itemValues["itemID"] == null ? 0 : int.Parse(itemValues["itemID"]);
            var review = reviewId == 0 ? new Review() : db.Reviews.Single(o=>o.ID==reviewId);
            review.Description = itemValues["Description"];
            review.Rating = byte.Parse(itemValues["Rating"]);
            review.Title = itemValues["Title"];
            if (review.ID==0)
            {
                review.Response = "";
                // New review? The Timestamp and LastUpdateDate are the same
                review.Timestamp = review.LastUpdateDate  = DateTime.Now;
                review.OwnerID = int.Parse(itemValues["OwnerID"]);
                review.RatedItemID = int.Parse(itemValues["RatedItemID"]);
                db = new RatedEntities();
                db.AddToReviews(review);
            }
            else
            {
                // An edit to an existing review? Update the LastUpdateDate only
                review.LastUpdateDate = DateTime.Now;
            }
            db.SaveChanges();
            return review;
        }


        public static Review Edit(NameValueCollection itemValues)
        {
            return StoreValues(itemValues);
        }
    }
}
